#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from utility.redis_client import RedisCacheClient
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class GameState:
    def __init__(self):
        # 内存中的玩家状态（用于快速访问）
        self.users = {}

        # Redis缓存数据库
        self.cache_db = RedisCacheClient()

        # 从数据库加载现有玩家数据到内存
        self._load_users_from_db()

    def _load_users_from_db(self):
        """从数据库加载所有玩家数据到内存"""
        try:
            users_data = self.cache_db.get_all_users()
            for user in users_data:
                self.users[user["user_id"]] = user["data"]
            logging.info(f"从数据库加载了 {len(users_data)} 个玩家数据")
        except Exception as e:
            logging.error(f"加载玩家数据时出错: {e}")

    def save_user_to_db(self, user_id):
        """将特定玩家数据保存到数据库"""
        if user_id in self.users:
            return self.cache_db.save_user(user_id, self.users[user_id])
        return False

    def load_user_from_db(self, user_id):
        """从数据库加载玩家数据到内存"""
        user_data = self.cache_db.load_user(user_id)
        if user_data:
            self.users[user_id] = user_data
            return user_data
        return None

    def sync_all_users_to_db(self):
        """将所有内存中的玩家数据同步到数据库"""
        success_count = 0
        for user_id in self.users:
            if self.cache_db.save_user(user_id, self.users[user_id]):
                success_count += 1
        return success_count
